/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useRef } from 'react';
import DragTable from '@/components/DragTable';
import ProTable from '@ant-design/pro-table';
import KbPublishModal from '@/components/_pages/ad/lottery/publish/components/KbPublishModal';
import { PlusOutlined } from '@ant-design/icons';
import { defColumns } from '../../utils/ad.lottery';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import type { ProFormInstance } from '@ant-design/pro-form';
import { searchLottery, onlineLottery, exportLottery, deleteLottery } from '@/services/ad/lottery';
import { useSelector } from 'umi';
import type { ConnectState } from '@/models/connect';
import { Button, message, Space, Typography, Popconfirm } from 'antd';
import { isString, isArray } from 'lodash';

const { Paragraph } = Typography;
const Index: React.FC = () => {
  const { winSize } = useSelector((state: ConnectState) => state.global);
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();

  const handleOnline = (data: any) => {
    const { id, status } = data;
    const operate_type = `${status}` === '1' ? 'offline' : 'online';
    onlineLottery({ id, operate_type }).then((res) => {
      const { code, msg } = res;
      if (code == 0) {
        message.success('操作成功');
        actionRef.current?.reload();
      } else {
        message.error(msg);
      }
    });
  };

  const handleExport = (lottery_id: string) => {
    exportLottery({ lottery_id }).then((res) => {
      const { code, data, msg } = res;
      if (code == 0) {
        window.open(data, '_self');
      } else {
        message.error(msg);
      }
    });
  };

  const handleDelete = (id: string) => {
    deleteLottery({ id }).then((res) => {
      const { code, msg } = res;
      if (code == 0) {
        message.success('删除成功');
        actionRef.current?.reload();
      } else {
        message.error(msg);
      }
    });
  };

  const columns: ProColumns[] = [
    ...defColumns,
    {
      title: '操作',
      valueType: 'option',
      width: winSize === 'xs' ? 50 : 200,
      fixed: 'right',
      align: 'center',
      render: (_, record) => {
        const { id, real_lottery_id, status, platform, prize_param: params } = record;
        const prize_param = isString(params) ? JSON.parse(params) : isArray(params) ? params : [];
        record.prize_param = prize_param.map((item: any) => {
          const { prize_type, page: dUrl = '', appid = '' } = item;
          const page = [dUrl, appid].join(',');
          return {
            ...item,
            page: prize_type === 'url' ? page : '',
          };
        });
        const lotteryStatus = `${status}` === '1';
        const lotteryStatusTxt = lotteryStatus ? '下线' : '上线';
        const prefix =
          platform === 'weikuaidi'
            ? '/pages-0/pages/welfare/lotterys/details'
            : '/pages/lotterys/details';
        return (
          <Space direction={winSize === 'xs' ? 'vertical' : 'horizontal'}>
            <Popconfirm
              title={`你确定${lotteryStatusTxt}吗？`}
              onConfirm={handleOnline.bind(null, record)}
            >
              <Button type='primary' size='small'>
                {lotteryStatusTxt}
              </Button>
            </Popconfirm>
            <KbPublishModal record={record} actionRef={actionRef}>
              <Button type='primary' size='small'>
                编辑
              </Button>
            </KbPublishModal>
            <Button type='primary' size='small' onClick={handleExport.bind(this, real_lottery_id)}>
              导出
            </Button>
            <Paragraph
              style={{ margin: 0 }}
              copyable={{
                text: prefix + '?activityId=' + real_lottery_id,
                format: 'text/plain',
                icon: [
                  <Button type='primary' size='small'>
                    路径
                  </Button>,
                  <Button disabled size='small'>
                    已复制
                  </Button>,
                ],
              }}
            ></Paragraph>
            <Popconfirm
              title={`你确定删除吗？`}
              disabled={lotteryStatus}
              onConfirm={handleDelete.bind(null, id)}
            >
              <Button danger size='small' disabled={lotteryStatus}>
                删除
              </Button>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];
  const onFinish = async (values: any) => {
    const { current: page, pageSize: size, ...rest } = values;
    const { code, data, msg } = await searchLottery({ page, size, ...rest });
    if (code == 0) {
      const { list, count: total } = data;
      return {
        total,
        data: list,
      };
    }
    message.error(msg);
    return {
      data: [],
    };
  };
  return (
    <>
      <DragTable>
        <ProTable
          actionRef={actionRef}
          formRef={formRef}
          rowKey='id'
          request={onFinish}
          columns={columns}
          options={false}
          scroll={{ x: 1200 }}
          pagination={{
            pageSize: 20,
            showSizeChanger: false,
          }}
          search={{
            collapseRender: () => <></>,
            collapsed: false,
            optionRender: (_, __, dom) => {
              return [
                ...dom.reverse(),
                <KbPublishModal key='new' actionRef={actionRef}>
                  <Button type='primary'>
                    <PlusOutlined /> 发布新抽奖
                  </Button>
                </KbPublishModal>,
                ,
              ];
            },
          }}
        />
      </DragTable>
    </>
  );
};

export default Index;
